package com.evan.review.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.evan.review.R;
import java.util.ArrayList;
import java.util.List;

/**
 * 发送方Fragment
 * 用于演示各种发送消息的方式
 */
public class SenderFragment extends Fragment {

    private static final String TAG = "SenderFragment";
    public static final String ACTION_SEND_MESSAGE = "com.evan.review.ACTION_SEND_MESSAGE";
    public static final String EXTRA_MESSAGE = "message";
    
    private TextView tvSenderLog;
    private MessageSendListener listener;
    private SharedViewModel viewModel;
    // 存储早期日志消息的列表
    private List<String> pendingLogs = new ArrayList<>();
    
    /**
     * 消息发送监听器接口
     */
    public interface MessageSendListener {
        void onMessageSent(String message);
    }
    
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        
        // 确保Activity实现了接口
        if (context instanceof MessageSendListener) {
            listener = (MessageSendListener) context;
            logToUi("成功连接到Activity的接口回调");
        } else {
            throw new ClassCastException(context.toString() 
                    + " 必须实现MessageSendListener接口");
        }
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_sender, container, false);
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tvSenderLog = view.findViewById(R.id.tv_sender_log);
        
        // 显示所有待处理的日志消息
        if (!pendingLogs.isEmpty()) {
            for (String log : pendingLogs) {
                appendLogToTextView(log);
            }
            pendingLogs.clear();
        }
        
        // 获取ViewModel
        viewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        logToUi("获取到共享ViewModel");
        
        // 监听ViewModel中的数据变化
        viewModel.getMessage().observe(getViewLifecycleOwner(), message -> {
            logToUi("SenderFragment通过ViewModel接收到消息: " + message);
        });
    }
    
    /**
     * 通过接口方式发送消息
     */
    public void sendMessageViaInterface(String message) {
        logToUi("通过接口发送消息: " + message);
        if (listener != null) {
            listener.onMessageSent(message);
        }
    }
    
    /**
     * 通过ViewModel发送消息
     */
    public void sendMessageViaViewModel(String message) {
        logToUi("通过ViewModel发送消息: " + message);
        viewModel.setMessage(message);
    }
    
    /**
     * 通过本地广播发送消息
     */
    public void sendMessageViaBroadcast(String message) {
        logToUi("通过广播发送消息: " + message);
        
        // 创建Intent并添加消息
        Intent intent = new Intent(ACTION_SEND_MESSAGE);
        intent.putExtra(EXTRA_MESSAGE, message);
        
        // 发送本地广播
        LocalBroadcastManager.getInstance(requireContext()).sendBroadcast(intent);
    }
    
    /**
     * 记录日志到UI
     */
    private void logToUi(String message) {
        if (tvSenderLog != null) {
            appendLogToTextView(message);
        } else {
            // 视图还未创建，将日志消息添加到待处理列表
            pendingLogs.add(message);
        }
    }
    
    /**
     * 将日志添加到TextView
     */
    private void appendLogToTextView(String message) {
        String currentLog = tvSenderLog.getText().toString();
        tvSenderLog.setText((currentLog.isEmpty() ? "" : currentLog + "\n") + message);
    }
    
    @Override
    public void onDetach() {
        super.onDetach();
        listener = null;
    }
} 